#!/usr/bin/env python3
# coding: utf-8
# File: GraphShow.py


'''创建展示页面'''


class GraphShow():
    def __init__(self):
        self.base = '''
    <html>
    <head>
      <script type="text/javascript" src="VIS/dist/vis.js"></script>
      <link href="VIS/dist/vis.css" rel="stylesheet" type="text/css">
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    </head>
    <body>

    <div id="VIS_draw"></div>

    <script type="text/javascript">
      var nodes = data_nodes;
      var edges = data_edges;

      var container = document.getElementById("VIS_draw");

      var data = {
        nodes: nodes,
        edges: edges
      };

      var options = {
          nodes: {
              shape: 'dot',
            //shape: 'diamond',
              size: 15,
              font: {
                  size: 15,
                  color: 'black'
              }
          },
          edges: {
              font: {
                  size: 10,
                  align: 'center'
              },
              color: 'gray',
              arrows: {
                  to: {enabled: true, scaleFactor: 0.8}
              },
              smooth: {enabled: true}
          },
          physics: {
              enabled: true
          }
      };

      var network = new vis.Network(container, data, options);

    </script>
    </body>
    </html>
    '''

    '''读取文件数据'''

    def create_page(self, events):
        nodes = []
        for event in events:
            nodes.append(event[0])
            nodes.append(event[1])
        node_dict = {node: index for index, node in enumerate(nodes)}

        data_nodes = []
        data_edges = []
        '''抽取保存6大属性赋值标题'''
        # 关键字
        keywords = ''
        # 高频词
        usedword = ''
        # 人物
        person = ''
        # 日期 --->暂未处理
        # datetime= ''
        # 机构
        organization = ''
        # 地名
        placename = ''
        # 標題
        titlename = ''
        # 标题内容
        titlething = ''
        # 存放所有信息的数组
        allstar = []
        for node, id in node_dict.items():
            data = {}
            if node == '关键词':
                keywords = id
                data["group"] = '关键词'
                data["id"] = id
                data["label"] = node
                data["color"] = '#F8F8FF'
                data["shape"] = 'box'
            elif node == '高频词':
                usedword = id
                data["group"] = '高频词'
                data["id"] = id
                data["label"] = node
                data["color"] = '#F8F8FF'
                data["shape"] = 'box'
            elif node == '人物':
                person = id
                data["group"] = '人物或代号'
                data["id"] = id
                data["label"] = node
                data["color"] = '#F8F8FF'
                data["shape"] = 'box'
            # if node == '日期':
            #     datetime=id
            elif node == '机构':
                organization = id
                data["group"] = '机构'
                data["id"] = id
                data["label"] = node
                data["color"] = '#F8F8FF'
                data["shape"] = 'box'
            elif node == '地名':
                placename = id
                data["group"] = '地名'
                data["id"] = id
                data["label"] = node
                data["color"] = '#F8F8FF'
                data["shape"] = 'box'
            elif node == '标题':
                titlename = id
                data["group"] = '标题'
                data["id"] = id
                data["label"] = node
                data["shape"] = 'box'
            else:
                data["group"] = 'Event'
                data["id"] = id
                data["label"] = node
            data_nodes.append(data)

        # 做非空判断，追加数据

        if keywords != "":
            allstar.append(keywords)
        if usedword != "":
            allstar.append(usedword)
        if person != "":
            allstar.append(person)
        # if datetime != "":
        #     allstar.append(datetime)
        if organization != "":
            allstar.append(organization)
        if placename != "":
            allstar.append(placename)

        for edge in events:
            data = {}
            data['from'] = node_dict.get(edge[0])
            data['label'] = ''
            data['to'] = node_dict.get(edge[1])
            # 获取标题关联的节点ip--->标题内容
            # if node_dict.get(edge[1]) == titlename:
            #     titlething = node_dict.get(edge[0])
            data_edges.append(data)
        # for edge in events:
        # 标题--->语义之间的关系指定
        # for star in allstar:
        #     data = {}
        #     data['from'] = titlething
        #     data['label'] = ''
        #     data['to'] = star
        #     data_edges.append(data)
        # 删除标题的累赘关系
        # for xxx in data_edges:
        #     if xxx['to'] == 1:
        #         data_edges.remove(xxx)

        # # 做全节点计数映射，并且分配归一化数值节点
        # alledgesnumber = []
        # for xxx in data_edges:
        #     alledgesnumber.append(xxx['from'])
        #     alledgesnumber.append(xxx['to'])
        # lists = list(set(alledgesnumber))
        # # # print("list================"+str(len(lists)),str(lists))
        # # # 做归一化映射
        # alledges = {}
        # for xxx in enumerate(lists):
        #     alledges[xxx[0] + 1] = xxx[1]
        # # print(str(alledges))
        # # print(str(data_nodes))
        # #2021年9月10日11:06:14
        # #节点数据归一化
        # for data in data_nodes:
        #     for alledge in alledges:
        #         if data['id'] == alledges[alledge]:
        #             data.update(id=alledge)
        # #关联数据归一化
        # for data in data_edges:
        #     for alledge in alledges:
        #         if data['from'] == alledges[alledge]:
        #             # data.update(from=alledge)
        #             data['from']=alledge
        #         if data['to'] == alledges[alledge]:
        #             data.update(to=alledge)
        # print(str(data_edges))
        # #判断有几个关键字段====================================
        #2021年9月9日23:46:45
        # zerokeywords =''
        # zerousedword =''
        # zeroperson =''
        # zeroorganization =''
        # zeroplacename =''
        # showNum = []
        # if len(allstar) < 5 and len(allstar)>0:
        #     for i in allstar:
        #         if i == keywords:
        #             zerokeywords = i+":"+keywords
        #         if i == usedword:
        #             zerousedword = i + ":" + usedword
        #         if i == person:
        #             zeroperson = i + ":" + person
        #         if i == organization:
        #             zeroorganization = i + ":" + organization
        #         if i == organization:
        #             zeroplacename = i + ":" + placename
        #             # print("i===========",i)
        #
        #
        # #设置保存字段
        # zerohourkeywords =''
        # zerohourusedword =''
        # zerohourperson =''
        # zerohourorganization =''
        # zerohourplacename =''
        # # 归一化替换关键字段
        # for xxx in alledges:
        #     if zerokeywords != '':
        #         if keywords == alledges.get(xxx):
        #             zerohourkeywords = xxx
        #     if zerousedword != '':
        #         if usedword == alledges.get(xxx):
        #             zerohourusedword = xxx
        #     if zeroperson != '':
        #         if person == alledges.get(xxx):
        #             zerohourperson = xxx
        #     if zeroorganization != '':
        #         if organization == alledges.get(xxx):
        #             zerohourorganization = xxx
        #     if zeroplacename != '':
        #         if placename == alledges.get(xxx):
        #             zerohourplacename = xxx
        #
        # # 归一化替换node集合
        # for data in data_nodes:
        #     if zerokeywords != '':
        #         if data.get('id') == keywords:
        #             data.update(id=zerohourkeywords)
        #     if zerousedword != '':
        #         if data.get('id') == usedword:
        #             data.update(id=zerohourusedword)
        #     if zeroperson != '':
        #         if data.get('id') == person:
        #             data.update(id=zerohourperson)
        #     if zeroorganization != '':
        #         if data.get('id') == organization:
        #             data.update(id=zerohourorganization)
        #     if zeroplacename != '':
        #         if data.get('id') == placename:
        #             data.update(id=zerohourplacename)






        # 做数据最后格式处理
        # for data in data_nodes:
            # 删除标题的累赘节点
            # if data.get('id') == titlename:
            #     data_nodes.remove(data)

            # 设置属性并设置二级标题
            # if data.get('id') == titlething:
            #     # data.update(font='60', size='120', shape='icon', level='1', pid='0', subids=allstar)
            #     data.update(font='60', size='120', shape='icon', level='1', pid='0')
            # 添加设置三级标签
            # if data.get('id') == keywords:
            #     data.update(subids=keywordlist, level='2', pid=titlething)
            # if data.get('id') == usedword:
            #     data.update(subids=usedwordlist, level='2', pid=titlething)
            # if data.get('id') == person:
            #     data.update(subids=personlist, level='2', pid=titlething,label='人物或代号')
            # if data.get('id') == organization:
            #     data.update(subids=organizationlist, level='2', pid=titlething)
            # if data.get('id') == placename:
            #     data.update(subids=placenamelist, level='2', pid=titlething)

        self.create_html(data_nodes, data_edges)

        # data_edges.append(data)
        return data_nodes, data_edges

    '''生成html文件'''

    def create_html(self, data_nodes, data_edges):
        f = open('graph_show.html', 'w+', encoding='utf-8')
        html = self.base.replace('data_nodes', str(data_nodes)).replace('data_edges', str(data_edges))

        f.write(html)
        f.close()
